package admin

import (
	"baokaobang/conf"
	"baokaobang/datasourse"
	"baokaobang/models"
	"baokaobang/utils"
	"encoding/json"
	"fmt"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"os"
	"strings"
)

type Trends struct {
	Ctx iris.Context
}

type TrendsListParam struct {
	PerPage int `json:"perPage"`
	CurPage int `json:"curPage"`
}

type TrendsUser struct {
	Id        int64  `json:"userId"`
	Name      string `json:"userName"`
	ShortName string `json:"userShortName"`
}

type TrendsCollege struct {
	Id   int64  `json:"collegeId"`
	Name string `json:"collegeName"`
	Code string `json:"collegeCode"`
}

type TrendsObj struct {
	models.Trends `xorm:"extends"`
	TrendsUser    `xorm:"extends"`
	TrendsCollege `xorm:"extends"`
}

func (c *Trends) OptionsList() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

// 获取动态列表
func (c *Trends) PostList() interface{} {
	trendsListParam := TrendsListParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错：%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &trendsListParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错：%s", err.Error()), "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, "无法连接服务器", "")
	}

	trendsList := make([]TrendsObj, 0)
	start := (trendsListParam.CurPage - 1) * trendsListParam.PerPage
	err = db.Table(new(models.Trends)).Alias("t").
		Join("LEFT", []string{"user", "u"}, "t.user_id = u.id").
		Join("LEFT", []string{"college", "c"}, "u.college_id = c.id").
		Desc("t.id").Limit(trendsListParam.PerPage, start).Find(&trendsList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取动态列表：%s", err.Error()), "")
	}

	total, err := db.Where("id > ?", 0).Count(new(models.Trends))
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取动态列表：%s", err.Error()), "")
	}

	for i, trends := range trendsList {
		commentList := make([]models.CommentObj, 0)
		err = db.Table(new(models.Comment)).Alias("c").
			Join("LEFT", []string{"user", "fu"}, "c.user_id = fu.id").
			Join("LEFT", []string{"user", "tu"}, "c.to_id = tu.id").
			Where("c.trends_id = ?", trends.Trends.Id).Find(&commentList)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("无法获取动态评论列表：%s", err.Error()), "")
		}
		trendsList[i].Trends.CommentList = commentList
		trendsList[i].Trends.CreatedShow = trends.Trends.Created.Format("01-02 15:04")
		pictures := strings.Split(trends.Trends.PictureList, ",")
		var pictureList []string
		for _, picture := range pictures {
			pictureList = append(pictureList, fmt.Sprintf("%s%s", conf.Domain, picture))
		}
		trendsList[i].Trends.Pictures = pictureList
	}

	data := map[string]interface{}{
		"total": total,
		"list":  trendsList,
	}

	return utils.CommonRes(20000, "成功获取动态列表", data)
}

func (c *Trends) OptionsDel() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *Trends) PostDel() interface{} {
	delParam := utils.DelParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &delParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}

	if len(delParam.Ids) <= 0 {
		return utils.CommonRes(1000, "请提供要删除项的id", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	ids := strings.Split(delParam.Ids, ",")
	for _, id := range ids {
		trends := new(models.Trends)
		db.ID(id).Get(trends)

		commentList := make([]models.Comment, 0)
		db.Where("`trends_id` = ?", id).Find(&commentList)
		for _, comment := range commentList {
			db.ID(comment.Id).Unscoped().Delete(comment)
		}

		thumbsUpList := make([]models.ThumbsUp, 0)
		db.Where("`trends_id` = ?", id).Find(&thumbsUpList)
		for _, thumbsUp := range thumbsUpList {
			db.ID(thumbsUp.Id).Unscoped().Delete(thumbsUp)
		}

		if len(trends.CoverPicture) > 0 {
			coverPicUrl := fmt.Sprintf("%s%s", conf.UploadPrefix.Front, trends.CoverPicture)
			_, err = os.Stat(coverPicUrl)
			if err == nil {
				os.Remove(coverPicUrl)
			}
		}

		if len(trends.VideoUrl) > 0 {
			videoUrl := fmt.Sprintf("%s%s", conf.UploadPrefix.Front, trends.VideoUrl)
			_, err = os.Stat(videoUrl)
			if err == nil {
				os.Remove(videoUrl)
			}
		}

		picList := strings.Split(trends.PictureList, ",")
		if len(picList) > 0 {
			for _, pic := range picList {
				picUrl := fmt.Sprintf("%s%s", conf.UploadPrefix.Front, pic)
				_, err = os.Stat(picUrl)
				if err == nil {
					os.Remove(picUrl)
				}
			}
		}

		db.ID(id).Unscoped().Delete(trends)
	}

	return utils.CommonRes(20000, "操作成功", "")
}
